package main.java;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.rmi.ServerException;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Server {
	private String md5Hash;

	private static String baseAddress;

	private static String uri;

	private CookieAwareWebClient authenticatedClient;

	private String loginPost;

	private String nucleus;

	private int tradePileSize;

	private int consumablesSize;

	private Persona persona;

	public Server(String mail, String pass, String paramString3) {
		loginPost = "email=" + URLEncode(mail) + "&password=" + URLEncode(pass);
		this.md5Hash = new EAMD5().md5(paramString3);
	}

	static {
		baseAddress = uri + "/ut/game/" + "fifa13" + '/';
		int[] arrayOfInt = new int[14];
		arrayOfInt[0] = 1000;
		arrayOfInt[1] = 50;
		arrayOfInt[2] = 10000;
		arrayOfInt[3] = 100;
		arrayOfInt[4] = 50000;
		arrayOfInt[5] = 250;
		arrayOfInt[6] = 100000;
		arrayOfInt[7] = 500;
		arrayOfInt[8] = 250000;
		arrayOfInt[9] = 1000;
		arrayOfInt[10] = 1000000;
		arrayOfInt[11] = 2000;
		arrayOfInt[12] = 100000000;
		arrayOfInt[13] = 5000;
	}

	public void selectPersona() throws Exception {
		String str = GetSessionId();
		this.authenticatedClient.addHeader("x-ut-sid", str);
		acquireSecurityCookie();
		getPileSizes();
	}

	public void getPileSizes() throws Exception {
		JSONArray localJSONArray = Post("clientdata/pileSize", "", "GET")
				.getJSONArray("entries");
		int i = 0;
		if (i >= localJSONArray.length())
			return;
		JSONObject localJSONObject = localJSONArray.getJSONObject(i);
		switch (localJSONObject.getInt("key")) {
		default:
		case 2:
		case 3:
		}
		while (true) {
			i++;
			// break;
			this.tradePileSize = localJSONObject.getInt("value");
			// continue;
			this.consumablesSize = localJSONObject.getInt("value");
		}
	}

	private JSONObject Load(String paramString) throws Exception {
		if (!paramString.startsWith("http:"))
			paramString = baseAddress + paramString;
		JSONObject localJSONObject = new JSONObject(
				readResponse(this.authenticatedClient.openRead(paramString)));
		int i = localJSONObject.optInt("code");
		if ((i != 0) && (i != 403))
			throw new ServerException(localJSONObject.getString("reason"));
		return localJSONObject;
	}
	
	private static long getServerTimestamp()
	  {
	    return System.currentTimeMillis() / 1000L;
	  }

	public void loadAccountInfo() throws Exception {
		String str = "http://www.ea.com/p/fut/a/" + persona.shard
				+ "/l/en_GB/s/p/ut/game/" + "fifa13"
				+ "/user/accountinfo?timestamp=" + getServerTimestamp();
		ArrayList<Persona> listPersonas = new ArrayList<Persona>();
		JSONArray localJSONArray1;
		int i;
		try {
			JSONObject localJSONObject1 = Load(str);
			localJSONArray1 = localJSONObject1.getJSONObject("userAccountInfo")
					.getJSONArray("personas");
			i = 0;
			if (i >= localJSONArray1.length())
				return;
		} catch (ServerException localServerException) {
//			while (localServerException.getCode() == 465)
//				;
			throw localServerException;
		}
		JSONObject localJSONObject2 = localJSONArray1.getJSONObject(i);
		Persona localPersona = new Persona();
		listPersonas.add(localPersona);
		localPersona.displayName = localJSONObject2.getString("personaName");
		localPersona.nucleusPersonaId = Integer.toString(localJSONObject2
				.getInt("personaId"));
		JSONArray localJSONArray2 = localJSONObject2
				.getJSONArray("userClubList");
		for (int j = 0;; j++) {
			if (j >= localJSONArray2.length()) {
				i++;
				break;
			}
			JSONObject localJSONObject3 = localJSONArray2.getJSONObject(j);
			if (localJSONObject3.getString("year").equals("2013")) {
				localPersona.platform = localJSONObject3.getString("platform")
						.intern();
				localPersona.clubName = localJSONObject3.getString("clubName");
			}
		}
	}

	private String SecurityURL() {
		return "http://www.ea.com/p/fut/a/card-" + persona.platform
				+ "/l/en_GB/s/p/ut/game/" + "fifa13" + "/phishing/validate";
	}

	private void acquireSecurityCookie() throws Exception {
		if ((persona.nucleusPersonaId != null)
				&& (persona.nucleusPersonaId.length() > 0))
			this.authenticatedClient
					.setSecurityCookie(persona.nucleusPersonaId);
		String str;
		do {
			// return;
			this.authenticatedClient.dropPhishingCookies();
			str = "answer=" + this.md5Hash;
			this.authenticatedClient.addHeader("Content-Type",
					"application/x-www-form-urlencoded");
		} while (readResponse(
				this.authenticatedClient.UploadData(SecurityURL(), "POST", str))
				.contains("200"));
		throw new Exception("Failed to get cookie");
	}

	private String GetSessionId() throws Exception {
		String str1 = "{ \"isReadOnly\": false, \"sku\": \"393A0001\", \"clientVersion\": 3, \"nuc\": "
				+ this.nucleus
				+ ", \"nucleusPersonaId\": "
				+ persona.nucleusPersonaId
				+ ", \"nucleusPersonaDisplayName\": \""
				+ persona.displayName
				+ "\", \"nucleusPersonaPlatform\": \""
				+ persona.platform
				+ "\", \"locale\": \"en-GB\", \"method\": \"idm\", \"priorityLevel\":4, \"identification\": { \"EASW-Token\": \"\" } }";
		String str2 = "";
		if (!persona.platform.equals("360"))
			str2 = "-" + persona.platform;
		JSONObject localJSONObject = Post("http://www.ea.com/p/fut/a/card"
				+ str2 + "/l/en_GB/s/p/ut/auth", str1, null);
		String str3 = localJSONObject.getString("protocol");
		String str4 = localJSONObject.getString("ipPort");
		uri = str3 + "://" + str4;
		baseAddress = uri + "/ut/game/" + "fifa13" + "/";
		return localJSONObject.getString("sid");
	}

	private String URLEncode(String paramString) {
		StringBuffer localStringBuffer = new StringBuffer();
		int i = 0;
		while (i < paramString.length()) {
			char c = paramString.charAt(i);
			if (Character.isLetterOrDigit(c))
				localStringBuffer.append(c);
			else
				localStringBuffer.append('%').append(Integer.toString(c, 16));
			i++;
		}
		return localStringBuffer.toString();
	}

	private JSONObject Post(String paramString1, String paramString2,
			String paramString3) throws IOException, ServerException,
			JSONException {
		this.authenticatedClient.addHeader("Content-Type", "application/json");
		this.authenticatedClient.addHeader("accept", "application/json");
		this.authenticatedClient
				.addHeader(
						"Referer",
						"http://cdn.easf.www.easports.com/uk/football/static/flash/futFifaUltimateTeamPlugin/FifaUltimateTeam.swf");
		if (paramString3 != null) {
			this.authenticatedClient.addHeader("x-http-method-override",
					paramString3);
			paramString1 = baseAddress + paramString1;
		}
		InputStream localInputStream = this.authenticatedClient.UploadData(
				paramString1, "POST", paramString2);
		this.authenticatedClient.removeHeader("Content-Type");
		this.authenticatedClient.removeHeader("accept");
		this.authenticatedClient.removeHeader("x-http-method-override");
		String str = readResponse(localInputStream);
		JSONObject localJSONObject;
		if (str.length() > 0) {
			localJSONObject = new JSONObject(str);
			int i = localJSONObject.optInt("code");
			if ((i != 0) && (i != 403))
				throw new ServerException(localJSONObject.getString("reason"));
		} else {
			localJSONObject = null;
		}
		return localJSONObject;
	}

	public void login() throws Exception {
		this.authenticatedClient = new CookieAwareWebClient();
		this.authenticatedClient.addHeader("Content-Type",
				"application/x-www-form-urlencoded");
		this.authenticatedClient.addHeader("Origin",
				"http://cdn.easf.www.easports.com");
		this.authenticatedClient
				.addHeader(
						"Referer",
						"http://cdn.easf.www.easports.com/uk/football/static/flash/futFifaUltimateTeamPlugin/FifaUltimateTeam.swf");
		this.authenticatedClient
				.addHeader(
						"User-Agent",
						"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.60 Safari/534.24");
		String rep = readResponse(this.authenticatedClient.UploadData(
				LoginURL(), "POST", this.loginPost));
		System.out.println("==> login : " + rep);
		if (rep.contains("failed=true"))
			throw new Exception("Login failed");
		persona = new Persona();
		persona.nucleusPersonaId = rep.substring(
				rep.indexOf("<nucleusId>") + 11, rep.indexOf("</nucleusId>"));
		persona.platform = rep.substring(rep.indexOf("<platform>") + 10,
				rep.indexOf("</platform>"));
		persona.displayName = rep.substring(rep.indexOf("<gamertag>") + 10,
				rep.indexOf("</gamertag>"));
		System.out.println("Persona : " + persona.toString());
		GetSessionId();
//		rep = readResponse(this.authenticatedClient.UploadData(PileTradeURL(),
//				"POST", this.loginPost));
//		System.out.println("==> pileTrade : " + rep);

	}

	private static String LoginURL() {
		return "https://www.ea.com/uk/football/services/authenticate/login";
	}

	private static String PileTradeURL() {
		return baseAddress + "tradepile";
	}

	public static String readResponse(InputStream paramInputStream)
			throws IOException {
		StringBuffer localStringBuffer = new StringBuffer();
		BufferedReader localBufferedReader = new BufferedReader(
				new InputStreamReader(paramInputStream));
		while (true) {
			String str = localBufferedReader.readLine();
			if (str == null)
				return localStringBuffer.toString();
			localStringBuffer.append(str);
		}
	}
}
